package com.example.interceptor;

import com.example.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * TokenInserceptor 类的描述信息
 *
 * @author 12427
 * @since 2025/6/8 13:53
 */
@Slf4j
@Configuration//配置类
public class TokenInserceptor implements HandlerInterceptor {
//    token拦截器
    @Override//目标资源前执行  true  放行 false  拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //        1.获取请求路径
        StringBuffer url = request.getRequestURL();
//        2.判断请求路径是否是登录请求
        if (url.toString().contains("/login")) {
            log.info("登录请求");
            return true;
        }
//        3.获取请求头中的token
        String token = request.getHeader("token");
//        4.判断token是否存在 ，不存在返回401
        if (token == null || token.isEmpty()) {
            log.info("请求头中缺少token");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
//        5.如果存在,校验令牌,校验失败返回401
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("请求头中缺少token");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
//        6.放行请求
        return true;
//        过滤器链  按照文件排序
    }
}
